﻿using Microsoft.Extensions.DependencyInjection;

namespace ConsoleApp.TestFunc.测试代码
{

    public static class DITest4
    {
        public interface ILogger
        {
            void Log(string message);
        }

        public class ConsoleLogger : ILogger
        {
            public void Log(string message)
            {
                Console.WriteLine($"Console: {message}");
            }
        }

        public class FileLogger : ILogger
        {
            public void Log(string message)
            {
                File.AppendAllText("log.txt", $"File: {message}\n");
            }
        }

        public class LoggerService
        {
            private readonly ILogger _logger;

            public LoggerService(ILogger logger)
            {
                _logger = logger;
            }

            public void LogMessage(string message)
            {
                _logger.Log(message);
            }
        }

        public static void Run()
        {
            // 使用示例
            var services = new ServiceCollection();
            services.AddTransient<ILogger, ConsoleLogger>(); // 使用控制台日志
            services.AddTransient<LoggerService>();
            // services.AddTransient<ILogger, FileLogger>(); // 使用文件日志

            var serviceProvider = services.BuildServiceProvider();
            /*using (var scope = serviceProvider.CreateScope())
            {
                var loggerService = scope.ServiceProvider.GetRequiredService<LoggerService>();
                loggerService.LogMessage("Hello");
            }*/
            var loggerService = serviceProvider.GetRequiredService<LoggerService>();
            loggerService.LogMessage("This is a log message");
        }
    }
}
